package com.hjw.weixun.action;

import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import weibo4j.http.AccessToken;
import weibo4j.http.RequestToken;
import weibo4j.oauth.WebOAuth;

import com.alisoft.xplatform.asf.cache.IMemcachedCache;
import com.hjw.weiuxn.util.DateJsonValueProcessor;
import com.hjw.weixun.cache.MemCacheManage;
import com.hjw.weixun.domain.Follower;
import com.hjw.weixun.domain.Message;
import com.hjw.weixun.domain.User;
import com.hjw.weixun.domain.Weixun;
import com.hjw.weixun.redis.RedisQueue;
import com.hjw.weixun.service.FollowerService;
import com.hjw.weixun.service.MessageService;
import com.hjw.weixun.service.UserService;
import com.hjw.weixun.service.WeixunService;
import com.hjw.weixun.service.impl.FollowerServiceImpl;
import com.hjw.weixun.service.impl.MessageServiceImpl;
import com.hjw.weixun.service.impl.UserServiceImpl;
import com.hjw.weixun.service.impl.WeixunServiceImpl;

/**
 * 信息管理
 * 
 * @author wangchangxin date 2011-8-9
 * 
 */
public class MessageAction extends GenericAction {

	private static final long serialVersionUID = 7249804172349463600L;

	private static final Integer ERROR = 0;

	private static final Logger logger = LoggerFactory
			.getLogger(MessageAction.class);

	private MessageService messageService;

	private Message message;

	private String path;

	private Weixun weixun;

	private List<Message> messageList;

	private List<User> followerList;

	private FollowerService followerService;

	private WeixunService weixunService;

	private UserService userService;

	private IMemcachedCache cache;

	private String oauth_verifier;

	// 无参构造函数
	public MessageAction() {

		messageService = MessageServiceImpl.getInstance();
		followerService = FollowerServiceImpl.getInstance();
		weixunService = WeixunServiceImpl.getInstance();
		userService = UserServiceImpl.getInstance();
		cache = MemCacheManage.getInstance().getCache();
	}

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return queryMessageList();
	}

	/**
	 * 从Session中取出用户当前发信息的WeixunID
	 * 
	 * @return
	 */
	private Integer getCurrentWeixunId() {

		Integer currentWeixunId = ERROR;

		// Session中获取用户
		Object userObj = super.getRequest().getSession().getAttribute("user");
		if (null == userObj) {
			return currentWeixunId;
		}
		User user = (User) userObj;

		if (null != (currentWeixunId = user.getWeixunid1())) {
			return currentWeixunId;
		}
		if (null != (currentWeixunId = user.getWeixunid2())) {
			return currentWeixunId;
		}
		if (null != (currentWeixunId = user.getWeixunid3())) {
			return currentWeixunId;
		}

		return currentWeixunId;
	}

	/**
	 * 发布信息
	 * 
	 * @return
	 */
	public String sendMessage() {
		User currentUser = super.getCurrentUser();

		if (null == currentUser
				|| null == (weixun = currentUser.getCurrentWeixun())) {
			return null;
		}

		// 获取发信息人的粉丝列表
		List<Follower> fows = followerService.getFollowers(weixun.getId());

		if (null != message) {

			// 将数据插入数据库存
			message.setPublishtime(new Date());
			message.setWeixun(weixun);
			int msgId = messageService.addMessage(message);
			message.setMsgid(msgId);

			// 将信息ID插入每个粉丝的队列中
			for (Follower follower : fows) {
				RedisQueue.Rpush(follower.getFollowerid(), msgId);
			}

			// 将信息存入memcache中
			// IMemcachedCache cache = MemCacheManage.getInstance().getCache();
			message.setWeixun(weixun);
			cache.put(String.valueOf(msgId), message);
			
			if(null != weixun.getAccessToken()){
				
				WebOAuth.update(weixun.getAccessToken(), message.getContent());
			}

			renderHtml("{\"success\":\"true\"}");
			return null;
		}
		renderHtml("{\"success\":\"false\"}");
		return null;
	}

	/**
	 * 回复（评论信息）
	 * 
	 * @return
	 */
	public String addBack() {

		User currentUser = super.getCurrentUser();

		// 如果回复信息对象为空 或者 Session中无用户
		if (null == message || null == currentUser) {
			return null;
		}

		Object msgObj = cache.get(String.valueOf(message.getPid()));

		if (null == msgObj) {
			return null;
		}

		Message parentMsg = (Message) msgObj;

		// 将回复信息持久化到数据库
		message.setUser(currentUser);
		message.setPublishtime(new Date());
		Integer msgid = messageService.addMessage(message);

		message.setMsgid(msgid);

		parentMsg.getBackMsgList().add(message);
		cache.put(String.valueOf(message.getPid()), parentMsg);
		msgObj = cache.get(String.valueOf(message.getPid()));

		JsonConfig config = new JsonConfig();
		config.registerJsonValueProcessor(Date.class,
				new DateJsonValueProcessor("MM月dd日     HH:mm"));
		config.setJsonPropertyFilter(new PropertyFilter() {
			public boolean apply(Object source, String name, Object value) {
				if (name.equals("message")) { // 要过滤的 ，Map对象中的
					return true;
				} else {
					return false;
				}
			}
		});

		String jsonStr = JSONArray.fromObject(message, config).toString();

		renderHtml("{\"success\" : \"true\", \"data\":" + jsonStr + "}");

		return null;
	}

	/**
	 * 进入发信息页面，并且查询出微讯账户发的信息
	 * 
	 * @return
	 */
	public String queryMessageList() {
		path = "message/manager.jsp";

		User currentUser;

		if (null == (currentUser = super.getCurrentUser())) {
			return null;
		}

		if (null != weixun) {

			if (null == (weixun = weixunService.getWeixunByPath(weixun))) {
				return null;
			}
			
			if(null != oauth_verifier){
				
				RequestToken resToken = (RequestToken)super.getRequest().getSession().getAttribute("resToken");
				if(null != resToken){
					AccessToken accessToken = WebOAuth.requstAccessToken(
							resToken, oauth_verifier);
					weixun.setAccessToken(accessToken);
					
				}
				
			}

			// 每进入一个微讯账户，更新Session中的User的Weixun
			currentUser.setCurrentWeixun(weixun);
			super.getRequest().getSession().setAttribute("user", currentUser);

			messageList = messageService.getMessageList(weixun);

			followerList = userService.getFollowedList(weixun);
		}

		// renderHtml("{\"success\":\"false\"}");
		return SUCCESS;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public Message getMessage() {
		return message;
	}

	public void setMessage(Message message) {
		this.message = message;
	}

	public List<Message> getMessageList() {
		return messageList;
	}

	public void setMessageList(List<Message> messageList) {
		this.messageList = messageList;
	}

	public Weixun getWeixun() {
		return weixun;
	}

	public void setWeixun(Weixun weixun) {
		this.weixun = weixun;
	}

	public List<User> getFollowerList() {
		return followerList;
	}

	public void setFollowerList(List<User> followerList) {
		this.followerList = followerList;
	}

	public String getOauth_verifier() {
		return oauth_verifier;
	}

	public void setOauth_verifier(String oauth_verifier) {
		this.oauth_verifier = oauth_verifier;
	}
	

}
